package com.reggie.service.facade.impl;

import com.reggie.common.enums.ResponseCode;
import com.reggie.common.exception.ReggieException;
import com.reggie.service.facade.ShortMessageFacade;
import com.reggie.service.util.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 手机短信服务实现类
 * </p>
 * 使用阿里云sms
 *
 * @author yth
 * @since 2023-06-11-15:13
 */
@Slf4j
@Service
public class ShortMessageFacadeImpl implements ShortMessageFacade {

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    @Value("${reggie.sms.sign-name}")
    private String SIGN_NAME;

    @Value("${reggie.sms.template-code}")
    private String TEMPLATE_CODE;

    @Override
    public void sendSMValidateCode(String phoneNum) {
        if (redisTemplate.opsForValue().get(phoneNum) != null) {
            throw new ReggieException(ResponseCode.CLIENT_ERROR, "操作太频繁，请稍后再试");
        }

        String validateCode = ValidateCodeUtils.generateValidateCode(4).toString();
        // 发短信
        /*
        SMSUtils.sendMessage(SIGN_NAME, TEMPLATE_CODE, phoneNum, validateCode);
         */
        redisTemplate.opsForValue().set(phoneNum, validateCode, 1, TimeUnit.MINUTES);
        log.info("发送短信验证码“{}”到“{}”", validateCode, phoneNum);
    }

}
